package com.ithiema.cookie;

import com.ithiema.utils.CookieUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

@WebServlet("/ServletLastTime")
public class ServletLastTime extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取所有的cookie
        Cookie[] cookies = request.getCookies();
        //判断你是否有名称为lastTimeCookie对象
        Cookie cookie = CookieUtils.findCookieByName("lastTime", cookies);
        response.setContentType("text/html;charset=utf-8");
        PrintWriter writer = response.getWriter();
        if (cookie == null) {
            writer.write("<h3>欢迎首次访问</h3>");

        } else {
            String time = cookie.getValue();
            writer.write("<h3>欢迎回来，您上次的访问的时间:" + time + "</h3>");
        }
        Cookie ck = new Cookie("lastTime", new Date().toLocaleString().replace(" ", ""));
        ck.setMaxAge(24 * 60 * 60 * 7);
        response.addCookie(ck);

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
